package model

import (
	"gitee.com/mkwchecking/sr-core/domain/model/vo"
	"golang.org/x/crypto/bcrypt"
)

type PasswdModel struct {
	Password     string   `json:"-" gorm:"size:256;comment:用户密码" search:"type:exact"` // 用户密码
	PassUpdateAt *vo.Time `json:"-" gorm:"comment:密码更新时间"`                            // 密码更新时间
	Salt         string   `json:"-" gorm:"size:256;comment:密码盐"`
}

func (p PasswdModel) Encrypt() (string, error) {
	return PasswordEncode(p.Password, p.Salt)
}

func (p PasswdModel) Verify(hash string) bool {
	return PasswordVerify(p.Password, p.Salt, hash)
}

func PasswordEncode(password, salt string) (string, error) {
	p, err := bcrypt.GenerateFromPassword([]byte(password+salt), bcrypt.DefaultCost)
	if err != nil {
		return "", err
	}

	return string(p), nil
}

func PasswordVerify(password, salt, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password+salt))
	return err == nil
}
